package com.sayimo.maker.commons.ali.sms;

import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;

import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.sayimo.maker.commons.ali.sms.constant.Constants;
import com.sayimo.maker.commons.ali.sms.constant.HttpSchema;
import com.sayimo.maker.commons.ali.sms.enums.Method;
import com.sayimo.maker.commons.utils.JSONUtil;
import com.sayimo.maker.commons.utils.PropertiesUtils;

public class AliSms {
	
	private final static String APP_KEY = PropertiesUtils.getValue("ALIYUN.SMS.APP_KEY"); //AppKey从控制台获取
    private final static String APP_SECRET = PropertiesUtils.getValue("ALIYUN.SMS.APP_SECRET"); //AppSecret从控制台获取
    private final static String SIGN_NAME = PropertiesUtils.getValue("ALIYUN.SMS.SIGN_NAME"); // 签名名称从控制台获取，必须是审核通过的
    private final static String TEMPLATE_CODE = PropertiesUtils.getValue("ALIYUN.SMS.TEMPATE_CODE"); //模板CODE从控制台获取，必须是审核通过的
    private final static String HOST = "sms.market.alicloudapi.com"; //API域名从控制台获取
    private final static String MINITE = "30"; //API域名从控制台获取
	
	/*private final static String APP_KEY = "23629271"; //AppKey从控制台获取
    private final static String APP_SECRET = "7c9540e56e5f9aece81a2f831855d719"; //AppSecret从控制台获取
    private final static String SIGN_NAME = "广东尚一科技"; // 签名名称从控制台获取，必须是审核通过的
    private final static String TEMPLATE_CODE = "SMS_45480129"; //模板CODE从控制台获取，必须是审核通过的
    private final static String HOST = "sms.market.alicloudapi.com"; //API域名从控制台获取
*/    
    
    private final static String ERRORKEY = "errorMessage";  //返回错误的key
    
    private static Logger logger = LogManager.getLogger(AliSms.class);
	
	private static Map<String, String> ReadResponseBodyContent(String body) {
        Map<String, String> map = new HashMap<String, String>();    
        try {
            JSONObject jsonObject = JSON.parseObject(body);
            if (null != jsonObject) {               
                for(Entry<String, Object> entry : jsonObject.entrySet()){
                    map.put(entry.getKey(), entry.getValue().toString());
                }               
            }
            if ("false".equals(map.get("success"))) {
                map.put(ERRORKEY, map.get("message"));
            }
        } catch (Exception e) {
            map.put(ERRORKEY, body);
        }
        return map;
    }
	
	 /**
     * @MethodName sendMsg
     * @Description 
     * 
     * 
     * @author chenpy
     * @date 20170209
     * @param phoneNum 目标手机号，多个手机号可以逗号分隔;
     * @param smsCode 验证码
     */
    private static void sendMsg(String phoneNum, String smsCode){
        String path = "/singleSendSms";

        Request request =  new Request(Method.GET, HttpSchema.HTTP + HOST, path, APP_KEY, APP_SECRET, Constants.DEFAULT_TIMEOUT);

        //请求的query
        Map<String, String> querys = new HashMap<String, String>();
        querys.put("SignName", SIGN_NAME);
        querys.put("TemplateCode", TEMPLATE_CODE);
        querys.put("RecNum", phoneNum);
        Map<String, String> paramMap = new HashMap<String, String>();
        paramMap.put("minute", MINITE);
        paramMap.put("code", smsCode);
        querys.put("ParamString", JSONUtil.writeValueAsString(paramMap));
        request.setQuerys(querys);

        try {
            Map<String, String> bodymap = new HashMap<String, String>();
            Response response = Client.execute(request);
            //根据实际业务需要，调整对response的处理
            if (null == response) {
                logger.info("no response");
            } else if (200 != response.getStatusCode()) {
            	logger.info("StatusCode:" + response.getStatusCode());
                logger.info("ErrorMessage:"+response.getErrorMessage());
                logger.info("RequestId:"+response.getRequestId());
            } else {
                bodymap = ReadResponseBodyContent(response.getBody());
                if (null != bodymap.get(ERRORKEY)) {
                    //当传入的参数不合法时，返回有错误说明
                    logger.info(bodymap.get(ERRORKEY));
                } else {
                    //成功返回map，对应的key分别为：message、success等
                    logger.info(JSON.toJSONString(bodymap));
                }
            }
        }catch (Exception e){
            logger.info(e.getMessage());
        }
    }
    
    /**
     * @MethodName send
     * @Description 
     * 
     * @author chenpy
     * @date 20170209
     * @param phoneNum 要发送的电话号码
     * @param smsCode 验证码
     */
    public static void send(String phoneNums, String smsCode){
    	AliSms.sendMsg(phoneNums, smsCode);
    }
}
